package com.dm.cloud.auth.service.impl;

import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.dm.cloud.core.config.CommonConstants;
import com.dm.cloud.core.exception.CustomException;
import com.dm.cloud.core.mode.UserMode;
import com.dm.cloud.core.service.user.CurrentUserService;
import com.dm.cloud.oauthlib.service.impl.OauthCurrentUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
@Primary
public class Oauth2CurrentUserServiceImpl extends OauthCurrentUserServiceImpl implements CurrentUserService{

    @Autowired
    private HttpServletRequest request;

    @Override
    public UserMode getCurrentUser() {
        if(StrUtil.isNotEmpty(request.getHeader(CommonConstants.AUTH_HEAD_KEY))){
            try {
                Object loginId = SaOAuth2Util.getLoginIdByAccessToken(request.getHeader(CommonConstants.AUTH_HEAD_KEY));
                Object user = StpUtil.getSessionByLoginId(loginId).get(CommonConstants.AUTH_USER_DETAIL);
                if(user==null){
                    throw new CustomException("认证信息校验已过期",401,null);
                }
                return (UserMode) user;
            }catch (CustomException e){
                throw e;
            }catch (Exception e){
                throw new CustomException("认证信息错误",401,null);
            }
        }else{
            return super.getCurrentUser();
        }
    }


}
